$(function () {
  $(document).on('click', '#login-btn', handleLogin);
  $(document).on('click', '.login-verify', freshCaptcha);
  $(document).on('keydown', 'input', enterLogin);

  function handleLogin(e) {
    var username = $('#username').val();
    var password = $('#password').val();
    var captcha = $('#captcha').val();
    if (!(username && password && captcha)) {

      return;
    }
    if (username.length !== 11 && (username.length !== 18)) {
      warning_prompt('账号必须是手机');
      return;
    }
    $.post('/api/login', {
      username: username,
      password: md5(password),
      verify: captcha,
    }).then(function (res) {
      if(_.get(res, 'code') === 0) {
        window.location = getQueryString('from') ? decodeURIComponent(getQueryString('from')) : '/home';
      }
    }).catch(function (res) {
      freshCaptcha();
    });
  }

  function freshCaptcha() {
    $.get('/api/loginCaptcha').then(function (res) {
      if (res.code === 0) {
        $('.login-verify').html(res.data);
      }
    });
  }

  function enterLogin(e) {
    if(e.keyCode === 13) {
      handleLogin();
    }
  }
});